import { LockOutlined, MobileOutlined, UserOutlined } from '@ant-design/icons';
import { Alert, message, Checkbox } from 'antd';
import React, { useState, useRef } from 'react';
import { useParams } from 'react-router-dom';
import { ProFormCaptcha, ProFormCheckbox, ProFormText, LoginForm } from '@ant-design/pro-form';
import { useIntl, history, FormattedMessage, Link, SelectLang, useModel } from 'umi';
import Footer from '@/components/Footer';
import { login, queryHospitalAttestation } from '@/services/ant-design-pro/api';
import { getFakeCaptcha } from '@/services/ant-design-pro/login';
import md5 from 'js-md5';
import loginB from '../../../../public/loginB.png'
import styles from './index.less';
import { Color } from '@antv/l7-react/lib/component/LayerAttribute';
import { getCode, loginMent, getAccessToken, bindUserPhone, getBindUser } from '../register/service';

const LoginMessage: React.FC<{
    content: string;
}> = ({ content }) => (
    <Alert
        style={{
            marginBottom: 24,
        }}
        message={content}
        type="error"
        showIcon
    />
);

const Login: React.FC = () => {
    const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
    const [type, setType] = useState<string>('account');
    const { initialState, setInitialState } = useModel('@@initialState');
    const intl = useIntl();
    const [on, setOn] = useState(false);
    const [weixinLogin, setweixinLogin] = useState(false);
    const [phone, setPhone] = useState('');
    const [phoneTwo, setPhoneTwo] = useState('');
    const [code, setCode] = useState('');
    const [codeTwo, setCodeTwo] = useState('');
    const [openId, setOpenId] = useState('');
    const [agreeToTerms, setAgreeToTerms] = useState(false);
    const [isCodeSent, setIsCodeSent] = useState(false);
    const [countdown, setCountdown] = useState(60);
    const myDivRef = useRef(null);
    const lightOn = () => {
        setOn(true)
        var obj = new window.WxLogin({
            self_redirect: true,
            id: 'myDivRef',
            appid: "wxaa6be8148f8526bc",
            scope: 'snsapi_login',
            redirect_uri: 'https://d-stage.yizhongxin.com.cn/oauth/WxLogin.html',
            state: 'STATE',
            style: "block",
            href: "https://d-stage.yizhongxin.com.cn/oauth/WxLogin.css"
        });
    }
    const lightOff = () => {
        setOn(false)

    };
    const codeData = async (codeValue: any) => {
        const msg = await getAccessToken({ appid: "wxaa6be8148f8526bc", code: codeValue })
        if (msg.code === 200) {
            if (msg.data?.openId) {
                getBindUserMent(msg.data?.openId)
            }

        } else {
            await setOpenId(msg.data?.openId)
            await setweixinLogin(true)
        }
    }

    const getCodeData = async () => {
        const msg = await getCode({ phone: phone });
        if (msg.code === 200) {
            setIsCodeSent(true);
            startCountdown();
            message.success('发送成功');
        } else {
            message.error(msg.msg);
        }
    }
    const getCodeDataTwo = async () => {
        const msg = await getCode({ phone: phoneTwo });
        if (msg.code === 200) {
            setIsCodeSent(true);
            startCountdown();
            message.success('发送成功');
        } else {
            message.error(msg.msg);
        }
    }
    const startCountdown = () => {
        const interval = setInterval(() => {
            setCountdown((prevCount) => prevCount - 1);
        }, 1000);
        setTimeout(() => {
            clearInterval(interval);
            setIsCodeSent(false);
            setCountdown(60);
        }, 60000);
    };
    const handleVerificationCodeChange = (event: any) => {
        setPhone(event.target.value);
    };
    const handleVerificationCodeChangeTwo = (event: any) => {
        setPhoneTwo(event.target.value);
    };
    const codeChange = (event: any) => {
        setCode(event.target.value);
    };
    const codeChangeTwo = (event: any) => {
        setCodeTwo(event.target.value);
    };
    const fetchUserInfo = async () => {
        const userInfo = await initialState?.fetchUserInfo?.();
        if (userInfo) {
            await setInitialState((s) => ({
                ...s,
                currentUser: userInfo,
            }));
        }
    };
    const lijibangding = async () => {
        const msg = await bindUserPhone({
            openId: openId,
            phone: phoneTwo,
            smsCode: codeTwo
        })
        if (msg.code === 200) {
            sessionStorage.clear();
            console.log(
                'login sessionStorage.getItem(`hosiptaAuthlId`)',
                sessionStorage.getItem(`hosiptaAuthlId`),
            );
            const defaultLoginSuccessMessage = intl.formatMessage({
                id: 'pages.login.success',
                defaultMessage: '登录成功！',
            });
            message.success(defaultLoginSuccessMessage);
            msg.currentAuthority = 'admin';
            sessionStorage.setItem(`currentUser`, JSON.stringify(msg.data));
            await fetchUserInfo();
            // console.log('hospitalMsg1111', msg.data.adminType == 2);
            /** 此方法会跳转到 redirect 参数所在的位置 */
            if (!history) return;
            //console.log('hospitalMsg', msg.data.adminType == 2);
            const { query } = history.location;
            const { redirect } = query as { redirect: string };
            history.push(redirect || '/');
            return;
        } else {
            setUserLoginState(msg);
        }
    }
    const getBindUserMent = async (openIdVas: any) => {
        const msg = await getBindUser({ openId: openIdVas })
        if (msg.code === 200) {
            sessionStorage.clear();
            console.log(
                'login sessionStorage.getItem(`hosiptaAuthlId`)',
                sessionStorage.getItem(`hosiptaAuthlId`),
            );
            const defaultLoginSuccessMessage = intl.formatMessage({
                id: 'pages.login.success',
                defaultMessage: '登录成功！',
            });
            message.success(defaultLoginSuccessMessage);
            msg.currentAuthority = 'admin';
            sessionStorage.setItem(`currentUser`, JSON.stringify(msg.data));
            await fetchUserInfo();
            // console.log('hospitalMsg1111', msg.data.adminType == 2);
            /** 此方法会跳转到 redirect 参数所在的位置 */
            if (!history) return;
            //console.log('hospitalMsg', msg.data.adminType == 2);
            const { query } = history.location;
            const { redirect } = query as { redirect: string };
            history.push(redirect || '/');
            return;
        } else {
            setweixinLogin(true)
        }
    }
    window.addEventListener('message', (event) => {
        try {
            codeData(event.data.code)
        } catch {

        }
        event.data
        console.log('Received message from iframe:', event.data);
        // 在这里处理接收到的消息
    });
    const getGogin = async (values: API.LoginParams) => {
        try {
            if (!agreeToTerms) {
                message.warning('请勾选《用户协议》和《隐私政策》');
                return false
            }
            if (phone == '') {
                message.warning('请填写手机号');
                return false
            }
            if (code == '') {
                message.warning('请填写验证码');
                return false
            }
            // 登录
            const msg = await loginMent({
                phone: phone,
                smsCode: code
            });
            console.log('msg----', msg);
            if (msg.code === 200) {
                sessionStorage.clear();
                console.log(
                    'login sessionStorage.getItem(`hosiptaAuthlId`)',
                    sessionStorage.getItem(`hosiptaAuthlId`),
                );
                const defaultLoginSuccessMessage = intl.formatMessage({
                    id: 'pages.login.success',
                    defaultMessage: '登录成功！',
                });
                message.success(defaultLoginSuccessMessage);
                msg.currentAuthority = 'admin';
                sessionStorage.setItem(`currentUser`, JSON.stringify(msg.data));
                await fetchUserInfo();
                // console.log('hospitalMsg1111', msg.data.adminType == 2);
                /** 此方法会跳转到 redirect 参数所在的位置 */
                if (!history) return;
                //console.log('hospitalMsg', msg.data.adminType == 2);
                const { query } = history.location;
                const { redirect } = query as { redirect: string };
                history.push(redirect || '/');
                return;
            }

            // 如果失败去设置用户错误信息
            setUserLoginState(msg);
        } catch (error) {
            console.log('error', error);
            // const defaultLoginFailureMessage = intl.formatMessage({
            //   id: 'pages.login.failure',
            //   defaultMessage: '登录失败，请重试！',
            // });
            // message.error(defaultLoginFailureMessage);
        }
    };
    const { status, type: loginType } = userLoginState;

    return (
        <div>
            {
                <div>
                    <div className={weixinLogin ? styles.hiddenTwo : styles.hidden}>
                        <div className={styles.shoujih} >
                            <div className={styles.inpyyTwo}>
                                <div className={styles.bangding}>手机号绑定</div>
                                <div className={styles.bangdingTwo}>为防止帐号丢失以及方便找回，建议你绑定手机号码后再使用</div>
                                <input className={styles.inputOnePP} type="text" placeholder='请输入手机号' value={phoneTwo} onChange={handleVerificationCodeChangeTwo} />
                                <div className={styles.inputTwoII}>
                                    <input type="text" value={codeTwo} placeholder='请输入验证码' onChange={codeChangeTwo} />
                                    {
                                        !isCodeSent ? <div className={styles.getCodeTwo} onClick={getCodeDataTwo}>获取验证码</div> :
                                            <div className={styles.getCodeTwo} style={{ backgroundColor: '#92e0c8' }} >{countdown}s后获取验证码</div>
                                    }
                                </div>

                            </div>
                            <div className={styles.dengluLLL} onClick={lijibangding}>立即绑定</div>
                        </div>
                    </div >
                    <div className={weixinLogin ? styles.hidden : styles.container}>
                        <div className={styles.yishengban}>医中心 · 医生版</div>
                        <div className={styles.loginBox}>
                            <div className={styles.topdeng}>
                                <div className={on ? styles.xuanzhong : styles.xuanzhongTwo} onClick={lightOn}>微信登录</div>
                                <div className={on ? styles.xuanzhongTwo : styles.xuanzhong} onClick={lightOff}>验证码登录</div>
                            </div>

                            <div className={!on ? '' : styles.hidden} >
                                <div className={styles.inpyy}>
                                    <input className={styles.inputOne} type="text" placeholder='请输入手机号' value={phone} onChange={handleVerificationCodeChange} />
                                    <div className={styles.inputTwo}>
                                        <input type="text" value={code} placeholder='请输入验证码' onChange={codeChange} />
                                        {
                                            !isCodeSent ? <div className={styles.getCode} onClick={getCodeData}>获取验证码</div> :
                                                <div className={styles.getCode} style={{ backgroundColor: '#92e0c8' }} >{countdown}s后获取验证码</div>
                                        }
                                    </div>
                                    <div className={styles.psiah}> <input
                                        type="checkbox"
                                        checked={agreeToTerms}
                                        onChange={() => setAgreeToTerms(!agreeToTerms)}
                                    /><span>我已阅读并同意 <span style={{ color: '#62C9A9' }}>《用户协议》</span>和 <span style={{ color: '#62C9A9' }}>《隐私政策》</span></span></div>
                                </div>
                                <div className={styles.denglu} onClick={getGogin}>登录</div>

                            </div>
                            <div className={!on ? styles.hidden : ''} style={{ position: 'relative' }}>
                                <div style={{ width: '400px', height: '400px', position: 'absolute', left: '15px', top: '40px' }} id='myDivRef'></div>
                            </div>
                        </div>
                        <div className={styles.fottre}>京ICP备2023005250号-4</div>
                    </div >
                </div>
            }
        </div >
    );
};

export default Login;
